package view.convenio;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

import model.entidades.Convenio;
import model.repositorio.ConvenioDAO;
import utils.Constantes;
import view.componentes.QuaseGenericoTableModel;
import controller.ControladorConvenio;
import controller.ControladorExcecao;


public class TelaPesquisarConvenio extends JDialog implements ActionListener {

	private static final long serialVersionUID = 1L;
	
	private JPanel panelNorte;
	private final JPanel panelCentro = new JPanel();
	private JPanel panelSul;
	
	private JLabel lblPesquisarConvenio;
	private JButton btnCancelar;
	private JTable tableResultadosPesquisa;
	private JRadioButton rdbtnAmbos;
	private JRadioButton rdbtnAtivo;
	private JRadioButton rdbtnInativo;
	private JScrollPane scrollPane;
	private JLabel lblResultadosPesquisa;

	private ControladorConvenio controladorConvenio;

	private ButtonGroup grupoSituacao;

	private QuaseGenericoTableModel<Convenio> pesquisaTableModel;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
						if ("Nimbus".equals(info.getName())) {
							UIManager.setLookAndFeel(info.getClassName());
							break;
						}else{
							UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
						}
					}
					TelaPesquisarConvenio window = new TelaPesquisarConvenio();
					window.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});		
	}

	/**
	 * Create the dialog.
	 */
	public TelaPesquisarConvenio() {
		setResizable(false);
		
		controladorConvenio = new ControladorConvenio(null);
		inicializaComponentes();
		realizaPesquisa(ConvenioDAO.SITUACAO_ATIVOS);
		
	}
	
	private void inicializaComponentes() {
		setBounds(100, 100, 600, 450);
		setResizable(false);
		setModal(true);
		setLocationRelativeTo(null);
		getContentPane().setLayout(new BorderLayout());
		panelCentro.setBackground(Color.WHITE);
		panelCentro.setBorder(new EmptyBorder(5, 0, 5, 5));
		getContentPane().add(panelCentro, BorderLayout.CENTER);
		
		lblResultadosPesquisa = new JLabel("Resultados da Pesquisa");
		lblResultadosPesquisa.setBorder(new EmptyBorder(0, 0, 0, 5));
		lblResultadosPesquisa.setHorizontalAlignment(SwingConstants.LEFT);
		lblResultadosPesquisa.setBackground(Color.LIGHT_GRAY);
		lblResultadosPesquisa.setFont(new Font("Tahoma", Font.PLAIN, 14));
		
		JLabel lblTextoDaPesquisa = new JLabel("Exibir:");
		
		scrollPane = new JScrollPane();
		scrollPane.setToolTipText("Clique duas vezes na linha para exibir o Conv\u00EAnio.");
		scrollPane.setBackground(Color.WHITE);
		scrollPane.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		
		JSeparator separator = new JSeparator();
		
		rdbtnAtivo = new JRadioButton("Ativo");
		rdbtnAtivo.setBackground(Color.WHITE);
		rdbtnAtivo.addActionListener(this);

		rdbtnInativo = new JRadioButton("Inativos");
		rdbtnInativo.setBackground(Color.WHITE);
		rdbtnInativo.addActionListener(this);

		rdbtnAmbos = new JRadioButton("Ambos");
		rdbtnAmbos.setBackground(Color.WHITE);
		rdbtnAmbos.addActionListener(this);
		
		grupoSituacao = new ButtonGroup();
		grupoSituacao.add(rdbtnAtivo);
		grupoSituacao.add(rdbtnInativo);
		grupoSituacao.add(rdbtnAmbos);
		grupoSituacao.setSelected(rdbtnAtivo.getModel(), true);
		
		GroupLayout gl_panelCentro = new GroupLayout(panelCentro);
		gl_panelCentro.setHorizontalGroup(
			gl_panelCentro.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panelCentro.createSequentialGroup()
					.addGap(9)
					.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
					.addGap(3))
				.addGroup(Alignment.LEADING, gl_panelCentro.createSequentialGroup()
					.addGap(10)
					.addGroup(gl_panelCentro.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panelCentro.createSequentialGroup()
							.addComponent(lblTextoDaPesquisa)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(rdbtnAtivo)
							.addGap(18)
							.addComponent(rdbtnInativo)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(rdbtnAmbos)
							.addContainerGap())
						.addGroup(gl_panelCentro.createParallelGroup(Alignment.TRAILING)
							.addGroup(Alignment.LEADING, gl_panelCentro.createSequentialGroup()
								.addComponent(lblResultadosPesquisa, GroupLayout.PREFERRED_SIZE, 563, GroupLayout.PREFERRED_SIZE)
								.addContainerGap())
							.addGroup(gl_panelCentro.createSequentialGroup()
								.addComponent(separator, GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)
								.addGap(4)))))
		);
		gl_panelCentro.setVerticalGroup(
			gl_panelCentro.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panelCentro.createSequentialGroup()
					.addGap(12)
					.addGroup(gl_panelCentro.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblTextoDaPesquisa)
						.addComponent(rdbtnAtivo)
						.addComponent(rdbtnInativo)
						.addComponent(rdbtnAmbos))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(separator, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(lblResultadosPesquisa)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
					.addContainerGap())
		);
		
		pesquisaTableModel = new QuaseGenericoTableModel<Convenio>(Convenio.class, new ArrayList<Convenio>(), Constantes.COLUNAS_PESQUISA_CONVENIO);
		tableResultadosPesquisa = new JTable(pesquisaTableModel);
		tableResultadosPesquisa.addMouseListener(new MouseAdapter() {  
		    public void mouseClicked(MouseEvent e) {  
		    	cliqueTabela(e);
		    }  
		});  
		tableResultadosPesquisa.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableResultadosPesquisa.getColumnModel().getColumn(1).setPreferredWidth(110);
		tableResultadosPesquisa.getColumnModel().getColumn(1).setMaxWidth(110);
		tableResultadosPesquisa.getColumnModel().getColumn(2).setPreferredWidth(60);
		tableResultadosPesquisa.getColumnModel().getColumn(2).setMaxWidth(60);
		
		scrollPane.setViewportView(tableResultadosPesquisa);
		panelCentro.setLayout(gl_panelCentro);
		{
			panelSul = new JPanel();
			panelSul.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(panelSul, BorderLayout.SOUTH);
			{
				btnCancelar = new JButton("Sair");
				btnCancelar.setActionCommand("Cancel");
				btnCancelar.addActionListener(this);
				panelSul.add(btnCancelar);
			}
		}
		{
			panelNorte = new JPanel();
			panelNorte.setForeground(Color.WHITE);
			panelNorte.setBackground(Color.BLUE);
			getContentPane().add(panelNorte, BorderLayout.NORTH);
			
			lblPesquisarConvenio = new JLabel("Conv\u00EAnios Cadastrados");
			lblPesquisarConvenio.setForeground(Color.WHITE);
			lblPesquisarConvenio.setFont(new Font("Tahoma", Font.BOLD, 18));
			panelNorte.add(lblPesquisarConvenio);
		}
		
	}//inicializaComponentes()
	
	private void cliqueTabela(MouseEvent e) {
		if (e.getClickCount() == 2) {  
            Point p = e.getPoint();  
            int row = tableResultadosPesquisa.rowAtPoint(p);
            Convenio convenio = pesquisaTableModel.getItemLinha(row);
			new TelaCadastrarConvenio(convenio).setVisible(true);
        } 
	}//cliqueTabela()
	
	@Override
	public void actionPerformed(ActionEvent event) {

		String comando = event.getActionCommand();
		
		if(comando.equalsIgnoreCase(btnCancelar.getActionCommand())){
			this.dispose();
		} else {
			
			String situacao = "";
			
			if(rdbtnAtivo.isSelected()) {
				situacao = ConvenioDAO.SITUACAO_ATIVOS;
			} else if (rdbtnInativo.isSelected()) {
				situacao = ConvenioDAO.SITUACAO_INATIVOS;
			} else if (rdbtnAmbos.isSelected()) {
				situacao = ConvenioDAO.SITUACAO_TODOS;
			}
			
			realizaPesquisa(situacao);
			
		}
	}//actionPerformed()
	
	private void realizaPesquisa(String situacao) {
		pesquisaTableModel.limpar();
		try {
			List<Convenio> lista = controladorConvenio.pesquisarConvenio(situacao);
			pesquisaTableModel = new QuaseGenericoTableModel<Convenio>(Convenio.class, lista, Constantes.COLUNAS_PESQUISA_CONVENIO);
			tableResultadosPesquisa.setModel(pesquisaTableModel);
			tableResultadosPesquisa.getColumnModel().getColumn(1).setPreferredWidth(110);
			tableResultadosPesquisa.getColumnModel().getColumn(1).setMaxWidth(110);
			tableResultadosPesquisa.getColumnModel().getColumn(2).setPreferredWidth(60);
			tableResultadosPesquisa.getColumnModel().getColumn(2).setMaxWidth(60);
			
		} catch (ControladorExcecao e) {
			JOptionPane.showMessageDialog(this, e.getMessage(), "Pesquisa", JOptionPane.PLAIN_MESSAGE );
		}
	}
}
